package com.googlecode.jmicroerp.wicket.components.grid;

import com.googlecode.jmicroerp.repository.GenericOrder;
import com.googlecode.jmicroerp.repository.GenericRestriction;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

/**
 *
 * @author alex
 */
public class GridDataProvider<T extends Serializable> extends
		SortableDataProvider<T, String> implements Serializable {
	private static final long serialVersionUID = 1L;
	private final GridAction<T> gridAction;
	private final Class<T> persistentClass;
	private List<GenericRestriction> genericProperties;
	private final List<GenericOrder> genericOrders;

	public GridDataProvider(Class<T> persistentClass, GridAction gridAction,
			List<GenericRestriction> genericProperties,
			List<GenericOrder> genericOrders) {
		super();
		this.persistentClass = persistentClass;
		this.gridAction = gridAction;
		if (genericProperties != null) {
			List<GenericRestriction> lista = new ArrayList<GenericRestriction>();
			lista.addAll(genericProperties);
			this.genericProperties = lista;
		}
		this.genericOrders = genericOrders;
	}

	public void addRestriction(GenericRestriction restriction) {
		if (genericProperties == null) {
			genericProperties = new ArrayList<GenericRestriction>();
		}
		if (genericProperties.contains(restriction)) {
			genericProperties.remove(restriction);
		}
		genericProperties.add(restriction);
	}

	public void removeRestriction(GenericRestriction restriction) {
		if (genericProperties == null) {
			return;
		}
		if (genericProperties.contains(restriction)) {
			genericProperties.remove(restriction);
		}

	}

	@Override
	public Iterator<T> iterator(long firstResult, long maxResults) {
		return gridAction.getList(persistentClass, genericProperties,
				genericOrders, getSort(), firstResult, maxResults);
	}

	@Override
	public long size() {
		return gridAction.getCount(persistentClass, genericProperties);
	}

	@Override
	public IModel<T> model(final T model) {
		return new LoadableDetachableModel<T>(model) {
			@Override
			protected T load() {
				return gridAction.load(persistentClass, model);
			}
		};
	}
}
